package com.itheima.mm.service.impl;

import com.itheima.mm.dao.*;
import com.itheima.mm.entity.QueryPageBean;
import com.itheima.mm.pojo.Catalog;
import com.itheima.mm.pojo.Course;
import com.itheima.mm.pojo.User;
import com.itheima.mm.service.CourseService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseDao courseDao;

    @Autowired
    private CatalogDao catalogDao;

    @Autowired
    private TagDao tagDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private QuestionDao questionDao;


    @Override
    public List<Course> findListAll() {
        /*先将读取Course*/
        List<Course> courseList = courseDao.findListAll();
        /*将Course补齐*/
        for (Course course : courseList) {

            course = replenishCourse(course);
        }

        return courseList;
    }

    @Override
    public List<Course> findListByPage(QueryPageBean queryPageBean) {

        List<Course> courseList= courseDao.findListByPage(queryPageBean);
        for (Course course : courseList) {

            course = replenishCourse(course);
        }
        return courseList;
    }

    @Override
    public Long findTotal(QueryPageBean queryPageBean) {

        return courseDao.findTotal(queryPageBean);
    }

    @Override
    public boolean delete(Integer courseId) {
        boolean b = true;
        Course courseById = courseDao.findCourseById(courseId);
        courseById = replenishCourse(courseById);
        if (courseById.getCatalogList().size()!=0){
            b=false;
        } else if (courseById.getTagList().size()!=0){
            b=false;
        } else {
            courseDao.delete(courseId);
        }

        return b;

    }

    @Override
    public void update(Course course) {
        courseDao.update(course);
    }

    @Override
    public void add(Course course) {
        courseDao.add(course);
    }


    private Course replenishCourse (Course course){
        course.setCatalogList(catalogDao.findListByCourseId(course.getId()));
        course.setTagList(tagDao.findListByCourseId(course.getId()));
        course.setCreator(userDao.findById(course.getUserId()).getUsername());
        course.setCatalogQty(catalogDao.findCatalogQty(course.getId()));
        course.setTagQty(course.getTagList().size());
        course.setQuestionQty(questionDao.findQuestionQty(course.getId()));
        return course;

    }
}
